import { Scene, RasterLayer, PointLayer, LineLayer, Marker, MarkerLayer } from '@antv/l7'
import { Map } from '@antv/l7-maps'
import { DrawEvent, DrawLine, DrawPoint } from '@antv/l7-draw'
import eventHub from '@/utils/eventHub'
import { getAssetsFile } from '@/utils'

/**
 * 初始化创建地图
 * @param { string } id
 * @param { config } object
 */
export function initMap(id, config) {
  return new Promise((resolve, reject) => {
    const scene = new Scene({
      id,
      logoVisible: false,
      map: new Map({
        ...config
      })
    })
    window.screen = screen
    resolve(scene)
  })
}

/**
 * @desc 给地图添加
 * 根据数组index值控制图层显示层级
 * @param { array } arr
 */
export function initLayer(scene, arr) {
  arr.map((item, index) => {
    const layer = new RasterLayer({
      zIndex: index,
      name: item.name
    }).source(item.url, {
      parser: {
        type: 'rasterTile',
        tileSize: 256
      }
    })
    scene.addLayer(layer)
  })
}

/**
 * 添加全局图片资源
 * 图片数组：[{path: '', name: ''}, {path: '', name: ''}]
 * @param { array } imageArr
 */
export function addImage(scene, imageArr) {
  imageArr.map((item) => {
    scene.addImage(item.name, item.path)
  })
}

/**
 * 添加点图层
 * 数据对象 [{longitude: '', latitude: '', level: 'xxx'}, {longitude: '', latitude: ', level: 'zzz'}]
 * @param { array } arr
 * 图层配置属性: {}
 * @param { object } config
 */
export function createPoint(scene, arr, config) {
  const pointLayer = new PointLayer(config.layerAttr)
    .source(arr, {
      parser: {
        type: 'json',
        x: 'longitude',
        y: 'latitude'
      }
    })
    .shape(config.shapeName, config.shapeArr)
    .size(config.size)
    .style(config.style)

  if (config.eventArr.length > 0) {
    config.eventArr.map((event) => {
      pointLayer.on(event, (e) => {
        eventHub.emit(config.layerAttr.name + '-' + event, e)
      })
    })
  }

  scene.addLayer(pointLayer)
  return pointLayer
}

export const createMarkerLayer = (scene, lngLatArr, img, width = 38.4, height = 48.8) => {
  const src = getAssetsFile(`monitor/${img}.png`)
  const el = document.createElement('div')
  el.innerHTML = `<div style="width: ${width}px;height: ${height}px;position: relative;"><img src="${src}" style="width:100%;height:100%;position: absolute;top: 6px; left: 0px"></div>`

  const marker = new Marker({ element: el }).setLnglat(lngLatArr)
  const markerLayer = new MarkerLayer({ zIndex: 100 })
  markerLayer.addMarker(marker)
  scene.addMarkerLayer(markerLayer)
  return markerLayer
}

export function createLine(scene, arr, config) {
  const featureArr = arr.map((item, index) => {
    return {
      type: 'Feature',
      properties: {
        标准名称: index,
        id: item.id
      },
      geometry: {
        type: 'MultiLineString',
        coordinates: [
          item.lonLat.split(';').map((ii) => {
            return ii.split(',').map(Number)
          })
        ]
      }
    }
  })
  const linearLayer = new LineLayer({})
    .source({
      type: 'FeatureCollection',
      features: featureArr
    })
    .size(4)
    .shape('line')
    .color('标准名称', ['#5B8FF9', '#5CCEA1', '#F6BD16'])
    .style({
      borderWidth: 0.4,
      borderColor: '#fff'
    })

  if (config.eventArr.length > 0) {
    config.eventArr.map((event) => {
      linearLayer.on(event, (e) => {
        eventHub.emit(config.layerAttr.name + '-' + event, e)
      })
    })
  }

  scene.addLayer(linearLayer)
  return linearLayer
}

export function drawPoint(scene, shape = 'circle', colorObj) {
  const { normal, hover, active } = colorObj
  const drawPointObj = new DrawPoint(scene, {
    multiple: true,
    style: {
      point: {
        normal: { size: 14, color: normal, shape },
        hover: { size: 14, color: hover, shape },
        active: { size: 14, color: active, shape }
      },
      zIndex: 9999
    }
  })
  drawPointObj.disable()
  return drawPointObj
}

export function drawLine(scene) {
  const drawLineObj = new DrawLine(scene, {
    distanceOptions: {
      showTotalDistance: true,
      showDashDistance: false,
      format: (meters) => {
        return +meters.toFixed(3) + 'm'
      }
    },
    multiple: false,
    showMidPoint: true // 可以新增加点
  })
  drawLineObj.disable()
  return drawLineObj
}

/**
 * 创建弹窗模板
 * @param { object} item
 * @param { string } flag
 * @returns { string }
 */

export function createPopupEle(item, flag) {
  const ele = document.createElement('div')
  if (flag == 'fireArea') {
    ele.innerHTML = `
    <div class="popup-wrapper">
      <div class="popup-title">${item.feature.name}</div>
      <div class="line"></div>
      <div class="popup-content">
        <div class="item">设备编号：<span class="num">${item.feature.code}</span></div>
        ${item.feature.type === '1' ? `<div class="item">关联灯杆数：<span class="num">${item.feature.deviceCount}</span>个</div>` : ''}
        ${item.feature.type === '2' ? `<div class="item">挂载设备数：<span class="num">${item.feature.deviceCount}</span>个</div>` : ''}
        ${item.feature.type === '3' ? `<div class="item">控制灯具数：<span class="num">${item.feature.deviceCount}</span>个</div>` : ''}
        <div class="item">现存故障：<span class="${item.feature.alarmTypeLabel ? 'error' : ''}">${item.feature.alarmTypeLabel || '无'}</span></div>
      </div>
    </div>
    `
    return ele
  }
}
